package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.constant.Constant;
import cn.wen.yinxiu.common.to.system.NoticeTO;
import cn.wen.yinxiu.common.to.works.SimpleWorksTO;
import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.server.protocol.Command;
import cn.wen.yinxiu.member.server.protocol.friend.AddFriendRequest;
import cn.wen.yinxiu.member.server.protocol.friend.AddFriendResponse;
import cn.wen.yinxiu.member.server.protocol.system.NoticeRequest;
import cn.wen.yinxiu.member.server.protocol.system.NoticeResponse;
import cn.wen.yinxiu.member.service.UsersService;
import cn.wen.yinxiu.member.vo.UserFriend;
import cn.wen.yinxiu.member.vo.UserInfo;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.Charset;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName: NoticeHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 通知类型处理类
 */
@Slf4j
@ChannelHandler.Sharable
public class NoticeHandler extends SimpleChannelInboundHandler<NoticeRequest> {

    private final UsersService userService;

    public NoticeHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NoticeRequest msg) {
        // 1.获取对方的管道 Channel
        Channel recipientChannel = SocketChannelUtil.getChannel(msg.getRecipientId());
        // 则不需要netty通知 只需要添加到通知中就行
        UserInfo meInfo = userService.queryUserInfo(msg.getSenderId());
        NoticeTO notice = new NoticeTO();
        notice.setActionType(msg.getActionType());
        notice.setContent(msg.getContent());
        notice.setRecipientId(msg.getRecipientId());
        notice.setSenderId(msg.getSenderId());
        notice.setSenderAvatar(meInfo.getUserAvatar());
        notice.setSourceId(msg.getSourceId());
        // 通知落到数据库
        NoticeTO noticeTO = userService.addNoticeInfo(notice);
        // 如果对方未上线
        if (null == recipientChannel) return;
        NoticeResponse noticeResponse = new NoticeResponse();
        BeanUtils.copyProperties(noticeTO, noticeResponse);
        noticeResponse.setSenderName(meInfo.getNickname());
        noticeResponse.setLastLoginTime(meInfo.getLastLoginTime());
        if (noticeTO.getSourceId() != null) {
            // 获取作品的信息
            SimpleWorksTO works = userService.getSimpleWorksInfo(noticeTO.getSourceId());
            if (works == null) {
                noticeResponse.setSourcePhoto("");
            } else {
                noticeResponse.setSourcePhoto(works.getCoverPath());
            }
        }
        JSONObject params = new JSONObject();
        params.put("userId", msg.getRecipientId());
        params.put("noticeInfo", noticeResponse);
        // 响应到对方的管道中
        recipientChannel.writeAndFlush(new TextWebSocketFrame(getByteBuf(ctx, Command.NoticeResponse, params)));
    }

    public ByteBuf getByteBuf(ChannelHandlerContext ctx, Byte type, JSONObject params) {
        ByteBuf bytebuf = ctx.alloc().buffer();
        JSONObject data = new JSONObject();
        data.put("type", type);
        data.put("code", 200);
        data.put("data", params);
        log.info("返回数据：{}", data);
        byte[] bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        bytebuf.writeBytes(bytes);
        return bytebuf;
    }
}
